# coding: utf-8
from subprocess import Popen, PIPE
from typing import AnyStr

from PySide6.QtCore import QThread, Signal


class ProcessThread(QThread):
    output = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.command: str = ''
        self.process: Popen = None
        self.__isStopped = False

    def run(self):
        self.process = Popen(self.command, text=True, stdout=PIPE, stderr=PIPE)
        while True:
            output = self.process.stdout.readline()
            if output == '' and self.process.poll() is not None:
                break
            if output:
                self.output.emit(output.strip())
            if self.__isStopped:
                break

    def communicate(self, input_=None, timeout=10):
        self.process.communicate(input_, timeout)

    def poll(self):
        return self.process.poll()

    def pid(self):
        return self.process.pid

    def stop(self):
        self.__isStopped = True
        self.process.terminate()
        self.process.kill()

    def terminate(self):
        self.stop()
        super().terminate()

    def write(self, command: AnyStr):
        self.command = command
        if not self.isRunning():
            self.start()
